
//
//  MusicLyricView.m
//  段子手
//
//  Created by dllo on 16/3/28.
//  Copyright © 2016年 JokesTeam. All rights reserved.
//

#import "MusicLyricView.h"

@interface MusicLyricView ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, copy) NSString *mStr;

@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *timeMutableArray;
@property (nonatomic, retain) NSMutableArray *lyricMutableArray;

@property (nonatomic, copy) NSString *timeStr;

@end

@implementation MusicLyricView

- (void)dealloc {
    [_mStr release];
    [_label release];
    [_tableView release];
    [_timeMutableArray release];
    [_lyricMutableArray release];
    [_timeStr release];
    [super dealloc];
}

- (void)dataHandel:(WXLUrlListModel *)model songName:(NSString *)songName singerName:(NSString *)singerName songID:(NSString *)songID {
    
    if (_lyricMutableArray.count) {
        [_lyricMutableArray removeAllObjects];
        [_timeMutableArray removeAllObjects];
        [_tableView reloadData];
    }
    _label.hidden = NO;
    _label.text = @"正在搜索歌词";
    NSString *urlStr = [NSString stringWithFormat:@"http://search.dongting.com/lyric/search?utdid=VGGJcU4veJsDACPAEYL62k1V&duration_ms=%.0f&song_id=%@&sign=3d5bfda9ecb3d7fee883ed9a7b591020&title=%@&artist=%@", model.duration * 1000, songID, songName, singerName];
    [WxlAPPTools GETWithURL:urlStr par:nil success:^(id responseObject) {
        NSArray *arr = responseObject[@"data"];
        
        if (!arr.count) {
            _label.text = @"歌词不存在";
            _label.hidden = NO;
        }
        
        for (NSDictionary *dic in arr) {
            NSString *urlStrLyric = [NSString stringWithFormat:@"http://search.dongting.com/lyric/content?utdid=VGGJcU4veJsDACPAEYL62k1V&title=%@&artist=%@&type=%@&lrcid=%@", dic[@"song_name"], dic[@"singer_name"], dic[@"type"], dic[@"_id"]];
            NSLog(@"%@", urlStrLyric);
            [WxlAPPTools GETWithURL:urlStrLyric par:nil success:^(id responseObject) {

                NSDictionary *dic = responseObject[@"data"];
                if (![dic isKindOfClass:[NSNull class]]) {
                    NSString *string1 = dic[@"content"];
                  
                    if (string1.length) {
                        
                        if ([[dic[@"type"] stringValue] isEqualToString:@"2"]) {
                            // 歌词解析
                            [self musicModelRequest:string1 type:[dic[@"type"] stringValue]];
                            return;
                        } if ([[dic[@"type"] stringValue] isEqualToString:@"3"]) {
                            // 歌词解析
                            [self musicModelRequest:string1 type:[dic[@"type"] stringValue]];
                            return;
                        }
                    }
                }
            } filed:^(NSError *error) {
                NSLog(@"error:%@", error);
                
            }];
        }
    } filed:^(NSError *error) {
       
        NSLog(@"error:%@", error);
    }];
}

- (void)musicModelRequest:(NSString *)str type:(NSString *)type {
    NSArray *array = [str componentsSeparatedByString:@"\n"]; //见到/n就把这个字符串放到数组中
    //区分时间与歌词
    self.timeMutableArray = [NSMutableArray new]; //接收时间
    self.lyricMutableArray = [NSMutableArray array]; //接收歌词
    
    for (NSString *string in array) {
        
        NSArray *timeAndLyric = [string componentsSeparatedByString:@"]"];//拆分时间与歌词
        
        if ([type isEqualToString:@"3"]) {
            NSMutableArray *lyArr = [NSMutableArray array];
            NSArray *tempArr1 = [timeAndLyric.lastObject componentsSeparatedByString:@"<"];
            self.mStr = [NSMutableString new];
            for (NSString *str in tempArr1) {
                
                if (!str.length) {
                    continue;
                }
                NSArray *tempArr2 = [str componentsSeparatedByString:@">"];
                [lyArr addObject:tempArr2.lastObject];
            }
            self.mStr = [lyArr componentsJoinedByString:@""];
        }
        if ([type isEqualToString:@"2"]) {
            self.mStr = [NSString stringWithFormat:@"%@", timeAndLyric.lastObject];
        }
        NSArray *timeArray = [timeAndLyric.firstObject componentsSeparatedByString:@"["];//拆分时间
      
        CGFloat time = [self stringTime:timeArray.lastObject];
        
        if (time > 1000) {
            time = 0.00;
        }
        NSString *timeStr = [NSString stringWithFormat:@"%.2f", time];
        
        [_timeMutableArray addObject:timeStr];
        [_lyricMutableArray addObject:_mStr];
        NSLog(@"%@", _timeMutableArray);
    }
   
    _label.hidden = YES;
    
    [self playMusicTime];
    
    [_tableView reloadData];
    return;
}


- (CGFloat)stringTime:(NSString *)timeStr {
    NSString *min = [timeStr componentsSeparatedByString:@":"].firstObject;
    NSString *sec = [timeStr componentsSeparatedByString:@":"].lastObject;

    CGFloat time = [min floatValue] * 60 + [sec floatValue];
    
    return time;
}

- (void)playMusicTime {
    [PLAYMUSIC.avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 10) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
    
        CGFloat current = CMTimeGetSeconds(PLAYMUSIC.avPlayItem.currentTime);  /**< 获取视频当前时间 */

        if (!_timeMutableArray.count) {
            return;
        }
        NSIndexPath *indexPath = [self lyricTableViewPlayTime:current];
        
        [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle]; //选中一行在中间
        
    }];
}




- (NSIndexPath *)lyricTableViewPlayTime:(CGFloat)time {
    
    for (NSInteger i = 0; i < _timeMutableArray.count; i++) {
        CGFloat lyTime = [_timeMutableArray[i] floatValue];
        if (time < lyTime) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:(i - 1 > 0 ? i - 1 : 0) inSection:0];
            
            return indexPath;
        }
    }
    //返回歌词indexPath
    return [NSIndexPath indexPathForRow:_timeMutableArray.count - 1 inSection:0];
}



#pragma mark - 子视图
- (void)createSubView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:(UITableViewStylePlain)];
    [self addSubview:_tableView];
    [_tableView release];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _tableView.userInteractionEnabled = NO;
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    [self addSubview:_label];
    [_label release];
    _label.backgroundColor = [UIColor clearColor];
    _label.textColor = [UIColor whiteColor];
    _label.text = @"正在搜索歌词";
    _label.textAlignment = NSTextAlignmentCenter;
    _label.hidden = YES;
    _label.font = [UIFont systemFontOfSize:24 weight:1];
    
}



#pragma mark - tableView Delegate & DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _lyricMutableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
//    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.text = _lyricMutableArray[indexPath.row];
    if (cell.selected) {
      
        cell.textLabel.textColor = [UIColor blueColor];
    } else {
        cell.textLabel.textColor = [UIColor whiteColor];
    }
    return cell;
}

+ (MusicLyricView *)musicLyricView:(CGRect)fram {
    return [[MusicLyricView alloc] initWithFrame:fram];
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        
        [self createSubView];
    }
    return self;
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
